package com.netty.clientserver.handler;

import com.netty.clientserver.util.ConnectUtils;
import com.netty.common.entity.result.Result;
import com.netty.common.enums.ExceptionEnum;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @author LiuXiaoYu
 * @date 2022/2/2- 14:00
 */

@Sharable
@Slf4j
public class NettyExceptionHandler extends ChannelDuplexHandler {
   public static final NettyExceptionHandler INSTANCE=new NettyExceptionHandler();

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof RuntimeException){
            //说明发生了异常
            log.info("全局异常处理器捕捉异常:{},message:{}",cause,cause.getMessage());
            ByteBuf byteBuf=ctx.alloc().buffer();
            //写错误信息返回
            byteBuf.writeBytes(Result.error(ExceptionEnum.ERROR,cause.getMessage()).toString().getBytes());
            ctx.channel().writeAndFlush(new TextWebSocketFrame(byteBuf));
            ConnectUtils.remove(ctx.channel());
        }
    }
}
